package org.boge.sharpdoc.service;

import org.boge.sharpdoc.dao.SendMailDao;
import org.boge.sharpdoc.bean.SendMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@Service
@Transactional
public class SendMailService {
    @Autowired
    private SendMailDao sendMailDao;

    public void sendMailCheckCode(String targetEmailAddr, String checkCode) throws MessagingException, UnsupportedEncodingException {
        SendMail senderInfo = sendMailDao.findInformation();
        Properties prop = new Properties();
        prop.setProperty("mail.host", senderInfo.getHost());
        prop.setProperty("mail.transport.protocol", senderInfo.getProtocol().toLowerCase());
        prop.setProperty("mail.smtp.auth", Boolean.toString(senderInfo.getAuthenticate()));
        prop.setProperty("mail.smtp.port", Integer.toString(senderInfo.getPort()));
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop);
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
        ts.connect(senderInfo.getHost(), senderInfo.getAddress(), senderInfo.getPassword());
        //4、创建邮件
        Message message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(senderInfo.getAddress(), senderInfo.getUsername(), "UTF-8"));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(targetEmailAddr));
        //邮件的标题
        message.setSubject("绑定邮箱验证码");
        //邮件的文本内容
        message.setContent(checkCode, "text/html;charset=UTF-8");
        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }

    public boolean updateEmail(SendMail mailInfo) {
        return sendMailDao.updateInformation(mailInfo) != 0;
    }

    public SendMail getEmailInfo() {
        return sendMailDao.findInformation();
    }
}